// pages/userInfo/myhouse/abouthouse/abouthouse.js
const app = getApp()
import api from '../../../../config/api'
import path from '../../../../config/path'

Page({
  data: {
    isEdit: false,
    houseId: null,
    loading: false,
    submitting: false,
    
    // 表单数据
    formData: {
      title: '',
      description: '',
      price: '',
      area: '',
      roomType: '',
      province: '',
      city: '',
      district: '',
      address: '',
      orientation: '',
      floor: '',
      totalFloor: '',
      decoration: '',
      facilities: []
    },
    
    // 图片相关
    picLocal: app.globalData.picLocal,
    uploadedImages: [],
    maxImageCount: 8,
    
    // 选择器数据
    roomTypes: ['一室', '一室一厅', '两室', '两室一厅', '三室', '三室一厅', '四室', '四室一厅', '其他'],
    orientations: ['东', '南', '西', '北', '东南', '东北', '西南', '西北', '南北通透'],
    decorations: ['毛坯', '简装', '精装', '豪装'],
    facilitiesList: [
      { name: '空调', value: '空调' },
      { name: '冰箱', value: '冰箱' },
      { name: '洗衣机', value: '洗衣机' },
      { name: '电视', value: '电视' },
      { name: '热水器', value: '热水器' },
      { name: '宽带', value: '宽带' },
      { name: '沙发', value: '沙发' },
      { name: '床', value: '床' },
      { name: '衣柜', value: '衣柜' },
      { name: '书桌', value: '书桌' },
      { name: '餐桌', value: '餐桌' },
      { name: '椅子', value: '椅子' },
      { name: '油烟机', value: '油烟机' },
      { name: '燃气灶', value: '燃气灶' },
      { name: '微波炉', value: '微波炉' },
      { name: '电磁炉', value: '电磁炉' },
      { name: '饮水机', value: '饮水机' },
      { name: '阳台', value: '阳台' },
      { name: '独立卫生间', value: '独立卫生间' },
      { name: '独立厨房', value: '独立厨房' },
      { name: '电梯', value: '电梯' },
      { name: '停车场', value: '停车场' },
      { name: '健身房', value: '健身房' },
      { name: '游泳池', value: '游泳池' }
    ]
  },

  onLoad: function (options) {
    console.log('abouthouse页面参数:', options)
    
    if (options && options.id) {
      this.setData({
        isEdit: true,
        houseId: options.id
      })
      wx.setNavigationBarTitle({ title: '编辑房源' })
      this.fetchHouseDetail(options.id)
    } else {
      wx.setNavigationBarTitle({ title: '发布房源' })
      this.setData({ loading: false })
    }
  },

  // 获取房源详情
  async fetchHouseDetail(houseId) {
    this.setData({ loading: true })
    
    try {
      console.log('获取房源详情，ID:', houseId)
      const res = await api.get('house', path.path.getHouseDetail + houseId)
      
      if (res.code === 200 && res.data) {
        const houseData = res.data
        console.log('房源详情数据:', houseData)
        this.setFormData(houseData)
      } else {
        throw new Error(res.message || '获取房源信息失败')
      }
    } catch (err) {
      console.log('获取房源详情失败:', err)
      wx.showToast({
        title: '加载房源信息失败',
        icon: 'none',
        duration: 2000
      })
      setTimeout(() => {
        wx.navigateBack()
      }, 1500)
    } finally {
      this.setData({ loading: false })
    }
  },

  // 设置表单数据
  setFormData(houseData) {
    console.log('设置表单数据:', houseData)
    
    // 解析设施信息
    let facilities = []
    try {
      if (houseData.facilities) {
        if (typeof houseData.facilities === 'string') {
          facilities = JSON.parse(houseData.facilities)
        } else {
          facilities = houseData.facilities
        }
      }
    } catch (e) {
      console.log('解析设施信息失败:', e)
      facilities = []
    }

    // 处理图片数据
    let uploadedImages = []
    if (houseData.picList && Array.isArray(houseData.picList)) {
      uploadedImages = houseData.picList.map(pic => {
        if (typeof pic === 'string') {
          return { url: pic, isLocal: false }
        } else {
          return { url: pic.url || pic.path, isLocal: false }
        }
      })
    }

    this.setData({
      formData: {
        title: houseData.title || '',
        description: houseData.description || '',
        price: houseData.price ? houseData.price.toString() : '',
        area: houseData.area ? houseData.area.toString() : '',
        roomType: houseData.roomType || '',
        province: houseData.province || '',
        city: houseData.city || '',
        district: houseData.district || '',
        address: houseData.address || '',
        orientation: houseData.orientation || '',
        floor: houseData.floor ? houseData.floor.toString() : '',
        totalFloor: houseData.totalFloor ? houseData.totalFloor.toString() : '',
        decoration: houseData.decoration || '',
        facilities: facilities
      },
      uploadedImages: uploadedImages
    })
  },

  // 表单输入处理
  onInputChange: function (e) {
    const { field } = e.currentTarget.dataset
    const value = e.detail.value
    
    this.setData({
      [`formData.${field}`]: value
    })
  },

  // 省市区选择
  onRegionChange: function (e) {
    const value = e.detail.value
    this.setData({
      'formData.province': value[0],
      'formData.city': value[1],
      'formData.district': value[2]
    })
  },

  // 选择器变化处理
  onPickerChange: function (e) {
    const { field } = e.currentTarget.dataset
    const value = e.detail.value
    
    let selectedValue = ''
    if (field === 'roomType') {
      selectedValue = this.data.roomTypes[value]
    } else if (field === 'orientation') {
      selectedValue = this.data.orientations[value]
    } else if (field === 'decoration') {
      selectedValue = this.data.decorations[value]
    }
    
    this.setData({
      [`formData.${field}`]: selectedValue
    })
  },

  // 设施选择处理 - 修复闪动问题
  toggleFacility: function (e) {
    const { value } = e.currentTarget.dataset
    const facilities = [...this.data.formData.facilities]
    const index = facilities.indexOf(value)
    
    if (index > -1) {
      facilities.splice(index, 1)
    } else {
      facilities.push(value)
    }
    
    this.setData({
      'formData.facilities': facilities
    })
  },

  // 选择图片
  chooseImages: function () {
    const { uploadedImages, maxImageCount } = this.data
    const remainingCount = maxImageCount - uploadedImages.length
    
    if (remainingCount <= 0) {
      wx.showToast({
        title: `最多只能上传${maxImageCount}张图片`,
        icon: 'none',
        duration: 2000
      })
      return
    }
    
    wx.chooseImage({
      count: remainingCount,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        const newImages = res.tempFilePaths.map(path => ({ url: path, isLocal: true }))
        this.setData({
          uploadedImages: [...this.data.uploadedImages, ...newImages]
        })
      },
      fail: (err) => {
        console.log('选择图片失败:', err)
        wx.showToast({
          title: '选择图片失败',
          icon: 'none',
          duration: 2000
        })
      }
    })
  },

  // 预览图片
  previewImage: function (e) {
    const { index } = e.currentTarget.dataset
    const urls = this.data.uploadedImages.map(img => img.url)
    
    wx.previewImage({
      urls: urls,
      current: urls[index]
    })
  },

  // 删除图片
  deleteImage: function (e) {
    const { index } = e.currentTarget.dataset
    
    wx.showModal({
      title: '确认删除',
      content: '确定要删除这张图片吗？',
      confirmColor: '#d81e06',
      success: (res) => {
        if (res.confirm) {
          const images = [...this.data.uploadedImages]
          images.splice(index, 1)
          this.setData({ uploadedImages: images })
        }
      }
    })
  },

  // 上传图片到服务器
  async uploadImages() {
    const { uploadedImages } = this.data
    const uploadedUrls = []
    
    const localImages = uploadedImages.filter(img => img.isLocal)
    if (localImages.length === 0) {
      return uploadedImages.map(img => img.url)
    }
    
    wx.showLoading({ title: '上传图片中...' })
    
    try {
      for (let i = 0; i < localImages.length; i++) {
        const image = localImages[i]
        
        const uploadRes = await new Promise((resolve, reject) => {
          wx.uploadFile({
            url: app.globalData.baseUrls.house + path.path.uploadPic,
            filePath: image.url,
            name: 'file',
            header: {
              'token': wx.getStorageSync('token') || ''
            },
            success: resolve,
            fail: reject
          })
        })
        
        const resData = JSON.parse(uploadRes.data)
        if (resData.code === 200) {
          uploadedUrls.push(resData.data)
        } else {
          throw new Error(resData.message || '上传失败')
        }
      }
    } catch (err) {
      console.log('上传图片失败:', err)
      throw new Error(`图片上传失败: ${err.message}`)
    } finally {
      wx.hideLoading()
    }
    
    const existingImages = uploadedImages.filter(img => !img.isLocal).map(img => img.url)
    return [...existingImages, ...uploadedUrls]
  },

  // 表单验证
  validateForm() {
    const { formData } = this.data
    
    if (!formData.title) {
      wx.showToast({
        title: '请输入房源标题',
        icon: 'none',
        duration: 2000
      })
      return false
    }
    
    if (!formData.price) {
      wx.showToast({
        title: '请输入租金价格',
        icon: 'none',
        duration: 2000
      })
      return false
    }
    
    const price = Number(formData.price)
    if (isNaN(price) || price <= 0) {
      wx.showToast({
        title: '请输入有效的租金价格',
        icon: 'none',
        duration: 2000
      })
      return false
    }
    
    const area = Number(formData.area)
    if (isNaN(area) || area <= 0) {
      wx.showToast({
        title: '请输入有效的房屋面积',
        icon: 'none',
        duration: 2000
      })
      return false
    }
    
    if (!formData.roomType) {
      wx.showToast({
        title: '请选择户型',
        icon: 'none',
        duration: 2000
      })
      return false
    }
    
    if (!formData.province || !formData.city || !formData.district) {
      wx.showToast({
        title: '请选择完整的省市区',
        icon: 'none',
        duration: 2000
      })
      return false
    }
    
    if (!formData.address) {
      wx.showToast({
        title: '请输入详细地址',
        icon: 'none',
        duration: 2000
      })
      return false
    }
    
    // if (this.data.uploadedImages.length === 0) {
    //   wx.showToast({
    //     title: '请至少上传一张房源图片',
    //     icon: 'none',
    //     duration: 2000
    //   })
    //   return false
    // }
    
    return true
  },

  // 准备提交数据
  prepareSubmitData() {
    const { formData, isEdit } = this.data
    
    const baseData = {
      title: formData.title,
      description: formData.description,
      price: Number(formData.price),
      area: Number(formData.area),
      roomType: formData.roomType,
      province: formData.province,
      city: formData.city,
      district: formData.district,
      address: formData.address,
      orientation: formData.orientation,
      decoration: formData.decoration,
      facilities: JSON.stringify(formData.facilities)
    }
    
    if (formData.floor) {
      baseData.floor = Number(formData.floor)
    }
    if (formData.totalFloor) {
      baseData.totalFloor = Number(formData.totalFloor)
    }
    
    if (isEdit) {
      baseData.id = this.data.houseId
    }
    
    return baseData
  },

  // 提交表单
  async onSubmit() {
    if (this.data.submitting) return
    
    if (!this.validateForm()) return
    
    this.setData({ submitting: true })
    wx.showLoading({ title: this.data.isEdit ? '更新中...' : '发布中...' })
    
    try {
      const uploadedImages = await this.uploadImages()
      const submitData = this.prepareSubmitData()
      
      console.log('提交数据:', submitData)
      
      let apiResult
      if (this.data.isEdit) {
        apiResult = await api.put('house', path.path.updateHouse, submitData)
      } else {
        apiResult = await api.post('house', path.path.publishHouse, submitData)
      }
      
      if (apiResult.code === 200) {
        const houseId = this.data.isEdit ? this.data.houseId : apiResult.data
        
        if (uploadedImages.length > 0) {
          await this.updateHouseImages(houseId, uploadedImages)
        }
        
        wx.showToast({
          title: this.data.isEdit ? '更新成功' : '发布成功',
          icon: 'success',
          duration: 1500
        })
        
        this.refreshPreviousPage()
        
        setTimeout(() => {
          wx.navigateBack()
        }, 1500)
      } else {
        throw new Error(apiResult.message || '操作失败')
      }
      
    } catch (err) {
      console.log('提交失败:', err)
      wx.showToast({
        title: err.message || '操作失败，请重试',
        icon: 'none',
        duration: 2000
      })
    } finally {
      this.setData({ submitting: false })
      wx.hideLoading()
    }
  },

  // 更新房源图片
  async updateHouseImages(houseId, imageUrls) {
    try {
      const updateData = {
        id: houseId,
        picList: imageUrls
      }
      await api.put('house', path.path.updateHouseImages, updateData)
    } catch (err) {
      console.log('更新房源图片失败:', err)
    }
  },

  // 刷新上一页
  refreshPreviousPage() {
    const pages = getCurrentPages()
    const prevPage = pages[pages.length - 2]
    if (prevPage && prevPage.fetchMyHouses) {
      prevPage.setData({
        houseList: [],
        pageData: {
          pageNo: 1,
          pageSize: 10,
          total: 0,
          hasMore: true
        }
      })
      prevPage.fetchMyHouses(true)
    }
  },

  // 重置表单
  onReset() {
    if (this.data.submitting) return
    
    wx.showModal({
      title: '确认重置',
      content: '确定要重置所有内容吗？',
      confirmColor: '#d81e06',
      success: (res) => {
        if (res.confirm) {
          this.setData({
            formData: {
              title: '',
              description: '',
              price: '',
              area: '',
              roomType: '',
              province: '',
              city: '',
              district: '',
              address: '',
              orientation: '',
              floor: '',
              totalFloor: '',
              decoration: '',
              facilities: []
            },
            uploadedImages: []
          })
        }
      }
    })
  }
})